package doc2db.interfaces.action;

import doc2db.Keey;
import doc2db.UserProp;
import doc2db.fileWorker.FileBeginer;
import doc2db.fileWorker.FileIO;
import doc2db.interfaces.action.save.SaveTxt;
import doc2db.interfaces.mainWindow.MyJEditorPane;
import doc2db.interfaces.mainWindow.VMemory;
import java.awt.Font;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Element;
import javax.swing.text.PlainView;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

/**
 *
 * @author yuriy
 * text/html
 */
public class CreateHtmlFile {
    /** if now data seted */
    public static final int ERROR = 0;
    /** if seted html text */
    public static final int HTML = 1;
    /** if seted plain text */
    public static final int TEXT = 2;

    private static int time = 0;
    protected JEditorPane text;
    protected String data[][];
    protected String headData[];

    public CreateHtmlFile(JEditorPane t, String [][] d, String [] h) {
        text = t;
        data = d;
        headData = h;
    }

    /**
     *  Set data into editors, and return type of text seted
     * @see CreateHtmlFile#ERROR
     * @see CreateHtmlFile#HTML
     * @see CreateHtmlFile#TEXT
     * @return type of text seted
     */
    public int setPage(){
        String arr [][] = new String[data.length + 1][headData.length];
        
        System.arraycopy(headData, 0, arr[0], 0, headData.length);
        for (int i = 0; i < data.length; i++) {
            System.arraycopy(data[i], 0, arr[i + 1], 0, data[i].length);
        }
        long ns = necessaryMem(arr);
        long avl = availableMem();
        if (ns <= avl) {
            this.setMyPage(this.addBodyTable());
            return HTML;
        } else {
            System.out.println("large table");
            
            SaveTxt st = new SaveTxt(null);
            boolean b = Keey.debug;

            Keey.debug = false;
            String str = st.getTextData(arr).append("\n\t")
                    .append(data.length).append(" rows").toString();
            Keey.debug = b;
            
            text.setContentType("text/plain");
            text.setEditorKit(new PlainViewEditorKit());
            text.setText(str);
            text.setFont(new Font(Font.MONOSPACED, 0, 14));
            text.setMinimumSize(text.getPreferredSize());

            initText();
            
            return TEXT;
        }
        //return ERROR;
    }

    private void initText() {
        if (text instanceof MyJEditorPane) {
            ((MyJEditorPane) text).table = data;
            ((MyJEditorPane) text).head = headData;
            ((MyJEditorPane) text).setOnRoot();
        }
    }

    public void setMyPage(String __text){
        time++;
        addDataToPane(__text);
    }

    private void addDataToPane(String htmltext) {
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        doc.getStyleSheet().addRule(getCSS());
        try {
            doc.setInnerHTML(doc.getDefaultRootElement(), htmltext);
        } catch (BadLocationException ex) {//this situation can hapen
            System.err.println(ex);
        } catch (IOException ex) {//this situation can hapen
            System.err.println(ex);
        }
        text.setEditorKit(kit);
        text.setDocument(doc);
        initText();
    }

    private String getFileName() {
        String s = "";
        if (isWindows()) {
            s = "C:\\\\" + "html" + time + ".html";
        } else {
            s = FileBeginer.resurse_users_usersFolder + Keey.sp + UserProp.user +
                    Keey.sp + "html" + time + ".html";
        }

        return s;
    }

    private void createFile(String fileName){
        FileIO.createFile(this.getFile(), fileName);
    }
    
    private String getFile(){
        StringBuffer textFile = new StringBuffer()
            .append("<HTML>\n")
            .append("<HEAD>\n")
            .append("<TITLE>html</TITLE>\n")
            .append("    <META http-equiv=\"Content-Type\" content=\"text/html;")
            .append(" charset=" + "UTF8\" />\n")//System.getProperty("file.encoding") + "\">\n");
            .append("<STYLE TYPE=\"text/css\">\n")
            .append(this.getCSS())
            .append("</STYLE>\n")
            .append("</HEAD>\n")
            .append("\n")
            //.append("<BODY>\n")
            ;
        textFile.append(this.addBodyTable());
        textFile//.append("</BODY>\n")
                .append("</HTML>\n");

        return textFile.toString();
    }

    private boolean isWindows(){
        if(System.getProperty("os.name").split(" ")[0].equals("Windows"))
            return true;
        else
            return false;
    }

    private String addBodyTable() {
        StringBuilder textFile = new StringBuilder()
                .append("<BODY>\n")
                .append("<table border=1> \n")
                .append("  <tr >\n");

        for (int j = 0; j < headData.length; j++) {
            textFile.append("    <th>\n");
            textFile.append("        <p>").append(headData[j]).append("</p>\n");
            textFile.append("    </th>\n");
        }

        textFile.append("  </tr>\n");

        for (int i = 0; i < data.length; i++) {
            textFile.append("  <tr>\n");
            for (int j = 0; j < data[i].length; j++) {
                textFile.append("    <td valign=top>\n");
                textFile.append("        ");
                //textFile.append("<a href=\"" + data[i][j].replace("\"", "&quot;") + "\">");
                textFile.append("<a href=\"").append(i).append(":").append(j).append("\">");
                textFile.append(data[i][j]
                        .replaceAll("&", "&amp;")
                        .replaceAll(">", "&gt;")
                        .replaceAll("<", "&lt;")
                        .replaceAll("\"", "&quot;")
                        .replaceAll("'", "&apos;")
                        .replaceAll("\n", " <br>")
                        .replaceAll("  ", "&nbsp;&nbsp;")
                        .replaceAll("\t", "<pre>&#09;<\\pre>")
                        .replaceAll("	", "<pre>&#09;<\\pre>"));
                textFile.append("</a>");
                textFile.append("\n");
                textFile.append("    </td>\n");
            }
            textFile.append("  </tr>\n");
        }

        textFile.append("</table>\n")
                .append("<p>(").append(data.length).append(" rows)</p>\n")
                .append("</BODY>\n");

        return textFile.toString();
    }

    private String getCSS() {
        return "" + FileBeginer.getCss();
        //return "" + FileIO.readFromFiles("" + FileBeginer.resurse_users_usersFolder + Keey.sp + UserProp.user + Keey.sp + FileBeginer.teamCssName);
    }

    private long availableMem() {
        Runtime run = Runtime.getRuntime();
        //long tot = run.totalMemory();
        //long free = run.freeMemory();
        long max = run.maxMemory();
        long ten = 10;
        return max - VMemory.MEGABYTE * ten;
    }

    private long necessaryMem(Object data[][]){
        long row = data.length;
        long col = data[0].length;
        long size = row * col;
        long koef = 200;
        return size / koef * VMemory.MEGABYTE;
    }

    /**
     *  It`s exted of default kit, but view factiory consists
     * only from PlainView.<br>
     * Use this editor kit is the same as,  call setLineWrap(true)
     * to JTextArea - sets the line-wrapping policy of the text area
     * to false, the lines will always be unwrapped.
     */
    private static class PlainViewEditorKit extends DefaultEditorKit {

        @Override
        public ViewFactory getViewFactory() {
            return new ViewFactory() {

                @Override
                public View create(Element elem) {
                    return new PlainView(elem);
                }
            };
        }


    }

}
